package algorithm;

import java.util.Stack;

/**
 * @version 1.0.0
 * Created by cyd on 2022-06-23 23:59:49
 * @ClassName : exam.WebsocketTest
 * @Description : 逆波兰表达式
 */
public class 逆波兰表达式 {

    public static void main(String[] args) {
        String[] tokens = new String[]{"2","1","+","4","*"};
        逆波兰表达式 test = new 逆波兰表达式();
        System.out.println(test.evalRPN(tokens));
    }

    public int evalRPN(String[] tokens) {
        // write code here
        int length = tokens.length;
        if (length == 1) {
            return Integer.parseInt(tokens[0]);
        }
        Stack<String> stack = turnToStack(tokens);

        while (stack.size() != 1) {
            getResult(stack);
        }
        String result = stack.pop();
        return Integer.parseInt(result);
    }

    private Stack<String> turnToStack(String[] tokens) {
        Stack<String> stack = new Stack<>();
        int length = tokens.length;
        for (int i = 0; i < length; i++) {
            String token = tokens[length - i - 1];
            stack.push(token);
        }
        return stack;
    }

    private void getResult(Stack<String> stack) {

        String a = stack.pop();
        String b = stack.pop();
        String oper = stack.pop();
        int count = count(a, b, oper);
        stack.push(String.valueOf(count));
    }


    private static int count(String a, String b, String oper) {

        switch (oper) {
            case "+":
                return Integer.parseInt(a) + Integer.parseInt(b);
            case "-":
                return Integer.parseInt(a) - Integer.parseInt(b);
            case "*":
                return Integer.parseInt(a) * Integer.parseInt(b);
            case "/":
                return Integer.parseInt(a) / Integer.parseInt(b);
            default:
                return 0;
        }
    }
}
